<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Auth\AuthManager;
use Illuminate\Http\Request;
use App\Core\Traits\Api\ApiResponse;
use Illuminate\Contracts\Auth\Factory as Auth;

class ApiAuthenticate
{
    use ApiResponse;

    /**
     * The authentication guard factory instance.
     *
     * @var \Illuminate\Contracts\Auth\Factory
     */
    protected $auth;

    /**
     * Create a new middleware instance.
     *
     * @param \Illuminate\Contracts\Auth\Factory $auth
     * @return void
     */
    public function __construct(Auth $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Handle an incoming request.
     * @param Request $request
     * @param \Closure $next
     * @param string|null $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = 'app')
    {
        $request->uid = 0;
        $oAuth = $this->auth->guard($guard);
        if ($oAuth->guest()) {
            return $this->unAuthorized();
        }
        $request->uid = $oAuth->id();
        return $next($request);
    }
}
